package com.miguo.framework.web;

import android.graphics.Bitmap;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.miguo.framework.utils.Log;
import com.miguo.framework.web.utils.WebUtils;

/**
 * Convenient extension of WebViewClient.
 */
public class CustomWebViewClient extends WebViewClient {

	private IWebViewClient mWebViewClient;

	public CustomWebViewClient(IWebViewClient WebViewClient) {
		super();
		mWebViewClient = WebViewClient;
	}

	/* 页面加载开始 */
	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {
		((CustomWebView) view).notifyPageStarted();
		mWebViewClient.onPageStarted(view, url, favicon);
		super.onPageStarted(view, url, favicon);
	}

	/* 页面加载结束 */
	@Override
	public void onPageFinished(WebView view, String url) {
		((CustomWebView) view).notifyPageFinished();
		mWebViewClient.onPageFinished(view, url);
		super.onPageFinished(view, url);
	}

	/* 页面加载资源 */
	@Override
	public void onLoadResource(WebView view, String url) {
		super.onLoadResource(view, url);
	}

	/* 页面加载失败 */
	@Override
	public void onReceivedError(WebView view, int errorCode,
			String description, String failingUrl) {
		Log.e("onReceivedError");
		mWebViewClient
				.onReceivedError(view, errorCode, description, failingUrl);
		super.onReceivedError(view, errorCode, description, failingUrl);
	}

	/* 链接请求 */
	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		if (url.startsWith("https://") || url.startsWith("http://")) {
			((CustomWebView) view).resetLoadedUrl();
			mWebViewClient.onUrlLoading(url);
			return false;
		} else if (isExternalApplicationUrl(url)) {
			mWebViewClient.onExternalApplicationUrl(url);
			return true;
		} else if (WebUtils.isValidURI(url)) {
			mWebViewClient.onExternalApplicationUri(url);
			return true;
		}
		return false;
	}

	private boolean isExternalApplicationUrl(String url) {
		return url.startsWith("vnd.") || url.startsWith("rtsp://")
				|| url.startsWith("itms://") || url.startsWith("itpc://")
				|| url.startsWith("intent://");
	}
}
